<template>
  <div class="app-container realtimeWaveformDiv">
    <el-container style="height: 100%;">
      <el-header style="height: 10%; text-align: center;">
        <span style="color: #fff; font-size: 4vh;">
          {{ clientNo }} 实时数据显示
        </span>
      </el-header>
      <el-main style="height: 85%; overflow: hidden;">
        <el-row :gutter="10" class="mb8" style="height: 100%;">
          <el-col :span="8" style="height: 100%;">
            <div id="IiChartDivId" class="echart" style="width: 100%; height: 90%;"></div>
          </el-col>
          <el-col :span="8" style="height: 100%;">
            <div id="positionChartDivId" class="echart" style="width: 100%; height: 90%;"></div>
          </el-col>
          <el-col :span="8" style="height: 100%;">
            <div id="angleChartDivId" class="echart" style="width: 100%; height: 90%;"></div>
          </el-col>
        </el-row>
      </el-main>
      <el-footer style="height: 5%;">

      </el-footer>
    </el-container>
  </div>
</template>

<style>
.html, body {
  height: 100%;
}
.realtimeWaveformDiv {
  height: 100%;
  background: url('../../../assets/images/visual/bg01.png') no-repeat;
  background-size: 100% 100%;
}
</style>

<script>
import echarts from 'echarts'
import mqtt from 'mqtt'
import { parseTime } from '../../../utils/ruoyi'

export default {
  name: "QuakeClientRealtimeWaveform",
  data() {
    return {
      // 遮罩层
      loading: true,
      IiChart: null,
      IiChartOption: null,
      positionChart: null,
      positionChartOption: null,
      angleChart: null,
      angleChartOption: null,
      IiData: [],
      positionData: {
        x: [],
        y: [],
        z: []
      },
      angleData: {
        x: [],
        y: [],
        z: []
      },
      timeData: [],
      /*
      [
        {
          'type': 'Ii',
          'data': 1.663
        },
        {
          'type': 'position',
          'data': {
            x: -1.32,
            y: 0.66,
            z: 2.39985
          }
        }
      ]
       */
      msgCache: [],
      clientNo: '+',
      mqttClient: null,
      broker: 'ws://47.94.80.3:61723',
      options: {
        connectTimeout: 40000,
        clientId: 'iot-quake-client',
        username: 'admin',
        password: 'keson-123',
        clean: true
      }
    };
  },
  created() {
    this.clientNo = this.$route.params.clientNo
    let time = this.getNowTime()
    this.IiData = [[time, 0]];
    this.positionData = {
      x: [[time, 0]],
      y: [[time, 0]],
      z: [[time, 0]]
    };
    this.angleData = {
      x: [[time, 0]],
      y: [[time, 0]],
      z: [[time, 0]]
    };
    this.timeData = [time];
    this.$nextTick(() => {
      this.IiChart = echarts.init(document.getElementById('IiChartDivId'));
      this.positionChart = echarts.init(document.getElementById('positionChartDivId'));
      this.angleChart = echarts.init(document.getElementById('angleChartDivId'));

      this.initIiChartData();
      this.initPositionChartData();
      this.initAngleChartData();
      this.initMqttClient();
      let _this = this;
      setInterval(function(){
        _this.updateData()
      }, 2000);

      window.addEventListener('resize', function(){
        _this.IiChart.resize();
        _this.positionChart.resize();
        _this.angleChart.resize();
      })
    });
  },
  methods: {
    initMqttClient(){
      let _this = this;
      _this.options.clientId = 'iot-quake-client-' + this.getNowTime();
      _this.mqttClient = mqtt.connect(_this.broker, _this.options)

      _this.mqttClient.on("connect", e => {
        console.log("mqttClient连接成功");
        _this.mqttClient.subscribe([ _this.clientNo + '/GET' ], error => {
          if (!error) {
            console.log("mqttClient订阅成功, topic:", _this.clientNo + '/GET');
          } else {
            console.log("mqttClient订阅失败, topic:", _this.clientNo + '/GET');
          }
        });
      });
      // 链接异常处理
      _this.mqttClient.on("error", error => {
        console.log("mqttClient连接失败，error:", error);
      });
      _this.mqttClient.on("disconnect", error => {
        console.log("mqttClient连接失败，disconnect:", error);
      });
      _this.mqttClient.on("close", error => {
        console.log("mqttClient连接失败，close:", error);
      });

      _this.mqttClient.on("message", (topic, message) => {
        // console.log("收到来自", topic, "的消息", message.toString());
        let msg = message.toString().split(/[(\r\n)\r\n]+/); // 根据换行或者回车进行识别
        for(let i=0; i< msg.length; i++){
          if(msg[i].startsWith('Ii=')){
            let Ii = {
              'type': 'Ii',
              'data': 0
            }
            let alertData = msg[i].split(',');
            for(let j = 0; j < alertData.length; j++){
              let val = new Number(alertData[j].split('=')[1]).toFixed(4);
              if(alertData[j].split('=')[0].startsWith('Ii')){
                Ii.data = val;
                break;
              }
            }
            _this.msgCache.push(Ii);
          }else if(msg[i].startsWith('position')){
            // 位移
            let position = {
              'type': 'position',
              'data': {
                x: 0,
                y: 0,
                z: 0
              }
            }
            let alertData = msg[i].split(',');
            for(let j = 0; j < alertData.length; j++){
              let val = new Number(alertData[j].split('=')[1]).toFixed(4);
              if(alertData[j].split('=')[0].startsWith('positionX')){
                position.data.x = val;
              }else if(alertData[j].split('=')[0].startsWith('positionY')){
                position.data.y = val;
              }else if(alertData[j].split('=')[0].startsWith('positionZ')){
                position.data.z = val;
              }
              _this.msgCache.push(position);
            }
          }else if(msg[i].startsWith('angle')){
            // 位移
            let angle = {
              'type': 'angle',
              'data': {
                x: 0,
                y: 0,
                z: 0
              }
            }
            let alertData = msg[i].split(',');
            for(let j = 0; j < alertData.length; j++){
              let val = new Number(alertData[j].split('=')[1]).toFixed(4);
              if(alertData[j].split('=')[0].startsWith('angleX')){
                angle.data.x = val;
              }else if(alertData[j].split('=')[0].startsWith('angleY')){
                angle.data.y = val;
              }else if(alertData[j].split('=')[0].startsWith('angleZ')){
                angle.data.z = val;
              }
              _this.msgCache.push(angle);
            }
          }
        }
      })
    },
    updateData(){
      let _this = this;
      let time = this.getNowTime();
      let Ii = [time, 0];
      let positionX = [time, 0];
      let positionY = [time, 0];
      let positionZ = [time, 0];
      let angleX = [time, 0];
      let angleY = [time, 0];
      let angleZ = [time, 0];
      if(_this.msgCache.length > 0){
        let msg = _this.msgCache[0]
        if(msg.type == 'Ii'){
          Ii = [time, msg.data];
        }else if(msg.type == 'position'){
          positionX = [time, msg.data.x]
          positionY = [time, msg.data.y]
          positionZ = [time, msg.data.z]
        }else if(msg.type == 'angle'){
          angleX = [time, msg.data.x]
          angleY = [time, msg.data.y]
          angleZ = [time, msg.data.z]
        }
        _this.msgCache.shift()
      }
      _this.timeData.push(time)
      _this.IiData.push(Ii)
      _this.positionData.x.push(positionX)
      _this.positionData.y.push(positionY)
      _this.positionData.z.push(positionZ)
      _this.angleData.x.push(angleX)
      _this.angleData.y.push(angleY)
      _this.angleData.z.push(angleZ)
      if(_this.timeData.length > 800){
        _this.timeData.shift();
        _this.IiData.shift();
        _this.positionData.x.shift()
        _this.positionData.y.shift()
        _this.positionData.z.shift()
        _this.angleData.x.shift()
        _this.angleData.y.shift()
        _this.angleData.z.shift()
      }

      _this.IiChart.setOption({
        series: [{
          data: _this.IiData
        }]
      });

      _this.positionChart.setOption({
        series: [
          {
            xAxisIndex: 0,
            yAxisIndex: 0,
            type: 'line',
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.x
          },
          {
            xAxisIndex: 1,
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.y
          },
          {
            xAxisIndex: 2,
            yAxisIndex: 2,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.z
          }
        ]
      });

      _this.angleChart.setOption({
        series: [
          {
            xAxisIndex: 0,
            yAxisIndex: 0,
            type: 'line',
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.x
          },
          {
            xAxisIndex: 1,
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.y
          },
          {
            xAxisIndex: 2,
            yAxisIndex: 2,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.z
          }
        ]
      });
    },
    getNowTime(){
      let date = new Date();
      let timestamp = date.getTime() + '';
      let len = timestamp.length;
      return parseTime(date, '{h}:{i}:{s}') + ':' + timestamp.substring(len-4, len-1);
    },
    initIiChartData(){
      let _this = this;
      _this.IiChartOption = {
        tooltip: {
          trigger: 'axis',
          position: function (pt) {
            return [pt[0], '10%'];
          }
        },
        title: {
          left: 'center',
          text: '震动数据曲线',
          textStyle: {
            color: 'white'
          }
        },
        xAxis: {
          name: '时间',
          type: 'category',
          boundaryGap: false,
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '数据值',
          boundaryGap: [0, '100%'],
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 80,
            end: 100
          },
          {
            start: 80,
            end: 100,
            bottom: '1%',
            textStyle: {
              color: "rgba(255, 255, 255, 1)"
            }
          }
        ],
        series: [
          {
            name: '数据值',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: _this.IiData
          }
        ]
      };

      _this.IiChart.setOption(_this.IiChartOption);
    },
    initPositionChartData(){
      let _this = this
      _this.positionChartOption = {
        animation: false,
        title: {
          left: 'center',
          text: '位移数据曲线',
          textStyle: {
            color: 'white'
          }
        },
        xAxis: [
          {
            gridIndex: 0,
            boundaryGap: false,
            type: 'category',
            name: 'X',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 1,
            boundaryGap: false,
            type: 'category',
            name: 'Y',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 2,
            boundaryGap: false,
            type: 'category',
            name: 'Z',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          }
        ],
        yAxis: [
          {
            gridIndex: 0,
            name: '数据值',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 1,
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 2,
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          }
        ],
        dataZoom: [
          {
            start: 90,
            end: 100,
            xAxisIndex: [0, 1, 2],
            bottom: '1%',
            textStyle: {
              color: "rgba(255, 255, 255, 1)"
            }
          }
        ],
        grid: [{
          top: '10%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }, {
          top: '38%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }, {
          top: '66%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }],
        series: [
          {
            xAxisIndex: 0,
            yAxisIndex: 0,
            type: 'line',
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.x
          },
          {
            xAxisIndex: 1,
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.y
          },
          {
            xAxisIndex: 2,
            yAxisIndex: 2,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.positionData.z
          }
        ]
      };
      _this.positionChart.setOption(_this.positionChartOption)
    },
    initAngleChartData(){
      let _this = this
      _this.angleChartOption = {
        animation: false,
        title: {
          left: 'center',
          text: '倾斜数据曲线',
          textStyle: {
            color: 'white'
          }
        },
        xAxis: [
          {
            gridIndex: 0,
            boundaryGap: false,
            type: 'category',
            name: 'X',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 1,
            boundaryGap: false,
            type: 'category',
            name: 'Y',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 2,
            boundaryGap: false,
            type: 'category',
            name: 'Z',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          }
        ],
        yAxis: [
          {
            gridIndex: 0,
            name: '数据值',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 1,
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          },
          {
            gridIndex: 2,
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            }
          }
        ],
        dataZoom: [
          {
            start: 90,
            end: 100,
            xAxisIndex: [0, 1, 2],
            bottom: '1%',
            textStyle: {
              color: "rgba(255, 255, 255, 1)"
            }
          }
        ],
        grid: [{
          top: '10%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }, {
          top: '38%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }, {
          top: '66%',
          left: '7%',
          right: '7%',
          bottom: '10%',
          height: '18%'
        }],
        series: [
          {
            xAxisIndex: 0,
            yAxisIndex: 0,
            type: 'line',
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.x
          },
          {
            xAxisIndex: 1,
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.y
          },
          {
            xAxisIndex: 2,
            yAxisIndex: 2,
            type: 'line',
            showSymbol: false,
            clip: true,
            lineStyle: {
              color: 'red'
            },
            data: _this.angleData.z
          }
        ]
      };
      _this.angleChart.setOption(_this.angleChartOption)
    }
  }
};
</script>
